<template>
  <!-- 分页器 -->
  <div class="pagination-page">
    <!-- 显示页数 -->
    <div class="showNum">
      <input v-model="currentPage" @keydown="keyDown" @blur="jump" oninput="value=value.replace(/[^\d]/g,'')"><span>/ {{totalPage}}</span>
    </div>
    <!-- 前进后退按钮 -->
    <div class="btns">
        <img :src="preImg"  @click="pre">
        <img :src="nextImg"  @click="next">
    </div>
  </div>
</template>

<script>
/*
    'pageSize': 一页展示条数
    回调事件
    'load': 改变当前页的回调，返回{currentPage: 当前页码, pageSize: 一页展示条数}
  */
import EventBus from '@/services/eventBus'
export default {
  props: ['pageSize'],
  data() {
    return {
      totalLine: 1,
      currentPage: 1,               // 当前页码
      totalPage: 1,                // 总共页码
      oldcurrentPage: 1              // 保存当前页码旧的值，即当前在第三页，输入框输入第三页，同一页，不发起刷新请求
    }
  },
  methods: {
    // 上一页
    pre() {
      this.currentPage > 1 && this.currentPage-- && this.load()
    },
    // 下一页
    next() {
      this.currentPage < this.totalPage && this.currentPage++ && this.load()
    },
    // 文本框按回车
    keyDown() {
      event.keyCode === 13 && this.jump()
    },
    // 跳转到某一页
    jump() {
      // 大于总页数显示总页数
      if (this.currentPage > this.totalPage) this.currentPage = this.totalPage
      // 小于1显示第一页
      if (this.currentPage < 1) this.currentPage = 1
      // 不等于旧的当前页，则重新刷新
      if (this.currentPage.toString() !== this.oldcurrentPage.toString()) this.load()
    },
    // 通知父组件，进行重新加载
    load() {
      this.oldcurrentPage = this.currentPage
      this.$emit('load', {currentPage: this.currentPage, pageSize: this.pageSize})
    }
  },
  computed: {
    // 上一页的按钮，小于等于1页则显示灰色按钮
    preImg() {
      return this.currentPage <= 1 ? require('@/assets/common/img/arrow_dis_left.png') : require('@/assets/common/img/arrow_left.png')
    },
    // 下一页的按钮，大于等于总页数则显示灰色按钮
    nextImg() {
      return this.currentPage >= this.totalPage ? require('@/assets/common/img/arrow_dis_right.png') : require('@/assets/common/img/arrow_right.png')
    }
  },
  mounted() {
    // 获取总条数
    this.$nextTick(() => {
      EventBus.$on('pageData', (pageData) => {
        this.totalPage = pageData.totalPage || 1
        this.currentPage = pageData.currentPage || 1
      })
    })
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus">
.pagination-page
  display flex

  .showNum
    display flex
    align-items center
    font-size 12px

    input
      width 46px
      outline none 
      border 0
      border-bottom 1px solid #d8dce5
      text-align right
      font-size 12px
      margin-right 5px
  
  .btns
    width 30px
    display flex
    align-items center
    justify-content space-between
    margin-left 15px

    img
      cursor pointer
</style>
